package com.example.weatherapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.example.weatherapp.databinding.ActivityWeatherBinding;
import com.example.weatherapp.gson.AQI;
import com.example.weatherapp.gson.BingPic;
import com.example.weatherapp.gson.Forecast;
import com.example.weatherapp.gson.NowWeather;
import com.example.weatherapp.gson.Suggest;
import com.example.weatherapp.gson.Tide;
import com.example.weatherapp.gson.Warning;
import com.example.weatherapp.util.DateUtil;
import com.example.weatherapp.util.HttpUtil;
import com.example.weatherapp.util.Utility;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.time.Instant;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class WeatherActivity extends AppCompatActivity {
    ActivityWeatherBinding binding;
    public static final String FORECAST_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/weather/7d";
    public static final String AQI_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/air/now";
    public static final String SUGGEST_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/indices/1d";
    public static final String NOWEATHER_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/weather/now";
    public static final String HOURLY_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/weather/24h";
    public static final String WARNING_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/warning/now";
    public static final String TIDE_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/ocean/tide";
    public static final String TIDE_HOURLY_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/ocean/tide/hour";
    public static final String GEO_URL = "https://mf78kxq93h.re.qweatherapi.com/v7/geo/lookup";
    public static final String KEY = "1afc41b4e57c43f78b61a165518b3fd0";
    private String current_province;
    private String current_city;
    private String current_county;
    private String type = "1,2,3,8";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        binding = ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Intent intent = getIntent();
        String weatherId = intent.getStringExtra("weather_id");
        current_province = intent.getStringExtra("current_province");
        current_city = intent.getStringExtra("current_city");
        current_county = intent.getStringExtra("current_county");
        binding.includeTitle.titleCity.setText(String.format("%s %s %s", current_province, current_city, current_county));
        requestWeather(weatherId);
        loadBingPic();
        binding.includeTitle.titleCity.setOnClickListener(v -> {
            binding.drawerLayout.openDrawer(GravityCompat.START);
        });
    }

    private void loadBingPic() {
        String url = "https://api.xygeng.cn/openapi/bing/";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast.makeText(WeatherActivity.this, "获取图片失败",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                BingPic bingPic = new Gson().fromJson(result, BingPic.class);
                Log.d("TAG123", result);
                runOnUiThread(() -> {
                    if (bingPic != null && bingPic.getCode() == 200) {
                        GlideApp.with(WeatherActivity.this)
                               .load(bingPic.getData().getUrl())
                               .transition(DrawableTransitionOptions.withCrossFade())
                               .error(R.drawable.ic_error)
                               .into(binding.bingPicImg);
                    } else {
                        Toast.makeText(WeatherActivity.this, "获取图片失败",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void requestWeather(String location) {
        loadBingPic();
        // 处理城市ID格式，移除前缀"CN"并确保一致性
        String locationId = location;
        if (location != null && location.startsWith("CN")) {
            locationId = location.substring(2);
        }
        
        Log.d("WeatherData", "Original location ID: " + location);
        Log.d("WeatherData", "Processed location ID: " + locationId);

        // 获取天气预报数据
        String url1 = FORECAST_URL + "?location=" + locationId + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(url1, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, 
                    "获取天气信息失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                Forecast forecast = Utility.headleForecastResponse(result);
                Log.d("TAG234", result);
                showForeastInfo(forecast);
                // 显示日出日落信息
                if (forecast != null && forecast.getDaily() != null && !forecast.getDaily().isEmpty()) {
                    showSunInfo(forecast.getDaily().get(0));
                }
            }
        });

        // 获取实时天气
        String url0 = NOWEATHER_URL + "?location=" + locationId + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(url0, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, 
                    "获取实时天气失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                NowWeather nowWeather = Utility.headleNowWeatherResponse(result);
                Log.d("TAG23", result);
                showNowWeatherInfo(nowWeather);
            }
        });

        // 获取空气质量
        String url2 = AQI_URL + "?location=" + locationId + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(url2, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, 
                    "获取空气质量失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                AQI aqi = Utility.headleAQIResponse(result);
                Log.d("TAG23456", result);
                showAQIInfo(aqi);
            }
        });

        // 获取生活指数
        String url3 = SUGGEST_URL + "?location=" + locationId + "&key=" + KEY + "&type=" + type;
        HttpUtil.sendOkHttpRequest(url3, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, 
                    "获取生活指数失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                Suggest suggest = Utility.headleSuggestResponse(result);
                Log.d("TAG2345666", result);
                showSuggestInfo(suggest);
            }
        });

        // 获取小时预报
        String url4 = HOURLY_URL + "?location=" + locationId + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(url4, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, 
                    "获取小时预报失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                HourlyWeather hourly = Utility.headleHourlyWeatherResponse(result);
                showHourlyInfo(hourly);
            }
        });

        // 获取预警信息
        String warningUrl = WARNING_URL + "?location=" + locationId + "&key=" + KEY;
        HttpUtil.sendOkHttpRequest(warningUrl, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(() -> Toast.makeText(WeatherActivity.this, 
                    "获取预警信息失败", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String result = response.body().string();
                Warning warning = Utility.handleWarningResponse(result);
                showWarningInfo(warning);
            }
        });

        // 加载景点信息
        loadAttractions();
    }

    private void loadAttractions() {
        runOnUiThread(() -> {
            View view = LayoutInflater.from(this).inflate(
                    R.layout.attraction_item, binding.includeAttractions.attractionsList, false);

            // 设置城市介绍
            binding.includeAttractions.attractionsTitle.setText(
                String.format("%s景点概览", current_city));
            binding.includeAttractions.attractionsDesc.setText(getDefaultCityDesc());

            // 添加推荐景点
            addAttractionItem("故宫博物院", 
                "世界上现存规模最大、保存最完整的木质结构古建筑群，中国明清两代的皇家宫殿。");
            
            addAttractionItem("天坛公园",
                "中国最大的古代帝王祭天建筑群，是明清两代帝王祭天、祈谷和祈雨的场所。");
            
            addAttractionItem("颐和园",
                "中国现存最大、保存最完整的皇家园林，被誉为皇家园林博物馆。");
        });
    }

    private void addAttractionItem(String name, String info) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.attraction_item, binding.includeAttractions.attractionsList, false);
        
        TextView nameText = view.findViewById(R.id.attraction_name);
        TextView infoText = view.findViewById(R.id.attraction_info);
        
        nameText.setText(name);
        infoText.setText(info);
        
        binding.includeAttractions.attractionsList.addView(view);
    }

    private String getDefaultCityDesc() {
        return current_city + "是一座历史文化名城，拥有众多著名的历史古迹和文化景点。这里不仅有古老的宫殿建筑，还有现代化的都市风貌，是一个极具观光价值的旅游胜地。";
    }

    private void showNowWeatherInfo(NowWeather nowWeather) {
        runOnUiThread(() -> {
            if (nowWeather != null && nowWeather.getCode().equals("200")) {
                String temp = nowWeather.getNow().getTemp();
                binding.includeNow.weatherInfoText.setText(nowWeather.getNow().getText());
                binding.includeNow.degreeText.setText(String.format("%s ℃", temp));
            } else {
                Toast.makeText(this, "获取实时天气信息出错！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showSuggestInfo(Suggest suggest) {
        runOnUiThread(() -> {
            if (suggest != null && suggest.getCode().equals("200")) {
                binding.includeSuggestion.comfortText.setText(String.format("舒适度指数：\n %s \n %s",
                        suggest.getDaily().get(3).getCategory(),
                        suggest.getDaily().get(3).getText()));
                binding.includeSuggestion.sportText.setText(String.format("运动指数：\n %s \n %s",
                        suggest.getDaily().get(0).getCategory(),
                        suggest.getDaily().get(0).getText()));
                binding.includeSuggestion.wearText.setText(String.format("穿衣指数：\n %s \n %s",
                        suggest.getDaily().get(2).getCategory(),
                        suggest.getDaily().get(2).getText()));
                
                // 添加旅游建议
                binding.includeSuggestion.travelCategory.setText(suggest.getDaily().get(1).getCategory());
                binding.includeSuggestion.travelText.setText(suggest.getDaily().get(1).getText());
            } else {
                Toast.makeText(this, "获取实时天气信息出错！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showAQIInfo(AQI aqi) {
        runOnUiThread(() -> {
            if (aqi != null && aqi.getCode().equals("200")) {
                binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
                binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());
            } else {
                Toast.makeText(this, "获取实时天气信息出错！", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void showForeastInfo(Forecast forecast) {
        runOnUiThread(() -> {
            if (forecast != null && forecast.getCode().equals("200")) {
                binding.includeForecast.forecastLayout.removeAllViews();
                for (Forecast.DailyDTO dailyDTO : forecast.getDaily()) {
                    View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                            binding.includeForecast.forecastLayout, false);
                    TextView dateText = (TextView) view.findViewById(R.id.date_text);
                    TextView infoText = (TextView) view.findViewById(R.id.info_text);
                    TextView maxText = (TextView) view.findViewById(R.id.max_text);
                    TextView minText = (TextView) view.findViewById(R.id.min_text);
                    dateText.setText(dailyDTO.getFxDate());
                    infoText.setText(dailyDTO.getTextDay());
                    maxText.setText(dailyDTO.getTempMax());
                    minText.setText(dailyDTO.getTempMin());
                    binding.includeForecast.forecastLayout.addView(view);
                }
            } else {
                Toast.makeText(this, "获取实时天气信息出错！", Toast.LENGTH_SHORT).show();
            }
        });

    }


    // 新增显示方法
    private void showHourlyInfo(HourlyWeather hourly) {
        runOnUiThread(() -> {
            if (hourly != null && hourly.getCode().equals("200")) {
                binding.includeHourly.hourlyLayout.removeAllViews();
                for (HourlyWeather.HourlyDTO item : hourly.getHourly()) {
                    View view = LayoutInflater.from(this).inflate(
                            R.layout.hourly_item, binding.includeHourly.hourlyLayout, false);

                    TextView timeText = view.findViewById(R.id.time_text);
                    TextView tempText = view.findViewById(R.id.temp_text);
                    TextView weatherText = view.findViewById(R.id.weather_text);

                    // 格式化时间显示
                    String originTime = item.getFxTime();
                    String formattedTime = DateUtil.formatHourlyTime(originTime);
                    timeText.setText(formattedTime);

                    tempText.setText(item.getTemp() + "℃");
                    weatherText.setText(item.getText());

                    binding.includeHourly.hourlyLayout.addView(view);
                }
            }
        });
    }

    private void showWarningInfo(Warning warning) {
        runOnUiThread(() -> {
            if (warning != null && warning.getCode().equals("200")) {
                LinearLayout warningList = binding.includeWarning.warningList;
                warningList.removeAllViews();

                if (warning.getWarning() == null || warning.getWarning().isEmpty()) {
                    // 显示无预警信息的提示
                    TextView noWarningText = binding.includeWarning.noWarningText;
                    noWarningText.setVisibility(View.VISIBLE);
                    return;
                }

                // 隐藏无预警信息的提示
                TextView noWarningText = binding.includeWarning.noWarningText;
                noWarningText.setVisibility(View.GONE);

                // 添加预警信息
                for (Warning.WarningDTO warningItem : warning.getWarning()) {
                    View view = LayoutInflater.from(this).inflate(
                            R.layout.warning_item, warningList, false);

                    TextView typeText = view.findViewById(R.id.warning_type);
                    TextView levelText = view.findViewById(R.id.warning_level);
                    TextView timeText = view.findViewById(R.id.warning_time);
                    TextView contentText = view.findViewById(R.id.warning_content);

                    typeText.setText(warningItem.getType());
                    levelText.setText(warningItem.getLevel());
                    timeText.setText(DateUtil.formatWarningTime(warningItem.getPubTime()));
                    contentText.setText(warningItem.getText());

                    warningList.addView(view);
                }
            }
        });
    }

    private void showSunInfo(Forecast.DailyDTO today) {
        runOnUiThread(() -> {
            if (today != null) {
                // 设置日出时间
                TextView sunriseText = findViewById(R.id.sunrise_time);
                if (sunriseText != null && today.getSunrise() != null) {
                    sunriseText.setText(today.getSunrise());
                }

                // 设置日落时间
                TextView sunsetText = findViewById(R.id.sunset_time);
                if (sunsetText != null && today.getSunset() != null) {
                    sunsetText.setText(today.getSunset());
                }

                // 计算并显示日照时长
                TextView daylightText = findViewById(R.id.daylight_duration);
                if (daylightText != null && today.getSunrise() != null && today.getSunset() != null) {
                    try {
                        String sunrise = today.getSunrise();
                        String sunset = today.getSunset();
                        
                        // 转换时间格式为分钟数
                        int sunriseMinutes = convertTimeToMinutes(sunrise);
                        int sunsetMinutes = convertTimeToMinutes(sunset);
                        
                        // 计算日照时长（分钟）
                        int daylightMinutes = sunsetMinutes - sunriseMinutes;
                        
                        // 转换为小时和分钟格式
                        int hours = daylightMinutes / 60;
                        int minutes = daylightMinutes % 60;
                        
                        daylightText.setText(String.format("%d小时%d分钟", hours, minutes));
                    } catch (Exception e) {
                        Log.e("SunInfo", "Error calculating daylight duration", e);
                        daylightText.setText("--");
                    }
                }
            }
        });
    }

    private int convertTimeToMinutes(String time) {
        try {
            String[] parts = time.split(":");
            if (parts.length == 2) {
                int hours = Integer.parseInt(parts[0]);
                int minutes = Integer.parseInt(parts[1]);
                return hours * 60 + minutes;
            }
        } catch (Exception e) {
            Log.e("SunInfo", "Error parsing time: " + time, e);
        }
        return 0;
    }
}
